import { ModalConfirm, TableLayout } from '@/components';
import { sysDictList } from '@/services/common';
import { monitorLimitsList, monitorLimitsRemove } from '@/services/deviceMsg';
import { PageContainer, ProFormText } from '@ant-design/pro-components';
import { Breadcrumb, Button, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { NavLink } from 'react-router-dom';
import ItemOption from './ItemOption';

const DeviceList = () => {
  const tableLayoutRef = useRef<any>(null);
  const [modItem, setModItem] = useState<any>({});
  const modalConfirmRef = useRef<any>(null);
  const itemOptionRef = useRef<any>(null);
  const [paginationTotal, setPaginationTotal] = useState(0);
  const [sysDictAgeListData, setSysDictAgeListData] = useState<any>([]);
  const [sysDictLevelListData, setSysDictLevelListData] = useState<any>([]);

  const getTableData = async (params?: any) => {
    const res = await monitorLimitsList(params);
    if (res?.code === 200) {
      setPaginationTotal(res.total);
      return res.rows;
    }
    return [];
  };
  const columns: any = [
    // 搜索
    {
      dataIndex: 'itemCode',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormText
            label="编码"
            placeholder="编码"
            fieldProps={{
              maxLength: 200,
            }}
          />
        );
      },
    },
    // 表格
    {
      title: '名称',
      dataIndex: 'itemName',
      hideInSearch: true,
    },
    {
      title: '编码',
      dataIndex: 'itemCode',
      hideInSearch: true,
    },
    {
      title: '最小值',
      dataIndex: 'lowerLimit',
      hideInSearch: true,
    },
    {
      title: '最大值',
      dataIndex: 'upperLimit',
      hideInSearch: true,
    },
    {
      title: '报警级别',
      dataIndex: 'level',
      hideInSearch: true,
      valueType: 'select',
      fieldProps: {
        options: sysDictLevelListData,
      },
    },
    {
      title: '报警开关',
      dataIndex: 'alarmSwitch',
      hideInSearch: true,
      render: (_: any, record: any) => (
        <>{record?.alarmSwitch == 1 ? '打开' : '关闭'}</>
      ),
    },
    {
      title: '年龄区间',
      dataIndex: 'ageArea',
      hideInSearch: true,
      valueType: 'select',
      fieldProps: {
        options: sysDictAgeListData,
      },
    },
    {
      title: '排序',
      dataIndex: 'sort',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 120,
      fixed: 'right',
      render: (_: any, record: any) => (
        <div className="custom-table-option">
          <a onClick={() => handleOption(record, 'edit')}>修改</a>
          <a className="danger" onClick={() => handleOption(record, 'delete')}>
            删除
          </a>
        </div>
      ),
    },
  ];
  // 删除操作
  const handleDelete = async () => {
    const res = await monitorLimitsRemove({
      id: modItem?.id || 0,
    });
    if (res?.code === 200) {
      message.success('操作成功');
      modalConfirmRef?.current?.handleModalShow();
      refreshList();
    }
  };
  // 操作栏操作
  const handleOption = (row: any, key: string) => {
    setModItem({
      ...row,
      modKey: key,
    });
    if (key === 'delete') {
      modalConfirmRef?.current?.handleModalShow('是否删除该报警限?');
    } else if (key === 'edit') {
      itemOptionRef?.current?.handleModalShow(row);
    }
  };
  const modalSuccessCallback = () => {
    if (modItem.modKey === 'delete') {
      handleDelete();
    }
  };
  const refreshList = () => {
    tableLayoutRef?.current?.tableReload();
  };
  const getsysDictListData = async () => {
    const res = await sysDictList({
      pageSize: 1000,
      pageNum: 1,
      itemClass: 'ageArea',
    });
    if (res?.code === 200) {
      const data = res.rows.map((its: any) => {
        return {
          label: its.itemName,
          value: its.itemValue,
        };
      });
      setSysDictAgeListData(data);
    }
    const resLevel = await sysDictList({
      pageSize: 10000,
      pageNum: 1,
      itemClass: 'monitorLimitsLevel',
    });
    if (resLevel?.code === 200) {
      const data = resLevel.rows.map((its: any) => {
        return {
          label: its.itemName,
          value: its.itemValue,
        };
      });
      setSysDictLevelListData(data);
    }
  };
  useEffect(() => {
    getsysDictListData();
  }, []);

  return (
    <PageContainer
      header={{
        title: <></>,
        ghost: true,
        breadcrumbRender: (route: any) => {
          return (
            <Breadcrumb
              items={[
                {
                  title: (
                    <div
                      style={{
                        display: 'flex',
                        alignContent: 'center',
                      }}
                    >
                      <NavLink to="/deviceThresholdMsg">报警限管理</NavLink>
                      <div
                        className="ant-breadcrumb-separator"
                        aria-hidden="true"
                      >
                        /
                      </div>
                      <div>报警限列表</div>
                    </div>
                  ),
                },
              ]}
            ></Breadcrumb>
          );
        },
      }}
    >
      <TableLayout
        ref={tableLayoutRef}
        getTableData={getTableData}
        headerTitle="报警限管理"
        toolBarRender={() => (
          <>
            <Button
              className="base-button"
              type="primary"
              onClick={() => itemOptionRef?.current?.handleModalShow()}
            >
              新增报警限
            </Button>
          </>
        )}
        columns={columns}
        rowKey={'id'}
        pagination={{
          total: paginationTotal,
        }}
      />
      {/* 确认弹层 */}
      <ModalConfirm
        ref={modalConfirmRef}
        successCallback={modalSuccessCallback}
      />
      {/* 添加编辑弹层 */}
      <ItemOption ref={itemOptionRef} refreshList={refreshList} />
    </PageContainer>
  );
};

export default DeviceList;
